var sha1 = require('sha1');
var config = require('../uteil')

//获取用户发送的消息
var { getUserData, formatData, formatDataJs } = require('../model/getUserData')
var replyMsg = require('../model/replyMsg')

let sha1Str = ''//服务端生成的signature
const { token, url } = config;

module.exports =  async (req, res, next) => {
  console.log('---');

  //  res.end('')
  // 1.拿到用户发送的数据
  let result = await getUserData(req)
  // 2.把xml数据格式化
  result = await formatData(result)
  // 3.把数据转化成对象
  result = formatDataJs(result)
  console.log('js', result);
  /* 
      ToUserName: 'gh_71b93b1e71b6',                  //公众号id
      FromUserName: 'okyqpv4JVsuU3CqE3j_lGV8yaNjw',   //用户id
      CreateTime: '1590314419',                       //时间戳
      MsgType: 'text',                                //消息类型
      Content: '123',                                 //消息内容
      MsgId: '22767831902656270'                      //消息id
  */


  /* 
   * @ 回复用户消息
  */
  let str = '';
  if (result.MsgType === 'text') {
    str = replyMsg({
      toUserName: result.FromUserName,
      fromUserName: result.ToUserName,
      date: Date.now(),
      type: 'text',
      content: '你好呀,收到了你发的文本信息'
    })
  } else if (result.MsgType === 'image') {
    str = replyMsg({
      toUserName: result.FromUserName,
      fromUserName: result.ToUserName,
      date: Date.now(),
      type: 'image',
      mediaId: result.MediaId,
    })
  }
  //回复用户消息
  res.send(str)

  // 验证是否微信服务器发送的消息，并回应给微信
  const { signature, echostr, timestamp, nonce } = req.query;
  sha1Str = sha1([timestamp, nonce, token].sort().join(''))
  if (sha1Str === signature) {
    return res.end(echostr)
  } else {
    return res.end('error')
  }

}